<template>
  <el-card>
    <el-form :model="formData" :inline="modelValue.inline" :label-position="modelValue.labelPosition || 'left'"
      label-suffix=":" :label-width="modelValue.labelWidth" ref="searchForm" @submit.native.prevent>
      <!-- 搜索项容器 -->
      <div class="search-items" :class="{ 'auto-fit': modelValue.autoFit }"
        :style="modelValue.autoFit ? {} : { flexWrap: 'wrap' }">
        <!-- 动态生成搜索项 -->
        <template v-for="(item, index) in modelValue.items" :key="index">
          <el-form-item v-if="item.isShow != false && expandStatus ? true : index < expandLimit" :label="item.label"
            :label-width="item.labelWidth || modelValue.labelWidth || '100px'"
            :style="{ flex: modelValue.autoFit ? '1' : 'unset', gridColumn: item.span ? `span ${item.span}` : '' }"
            class="form-item">


            <div v-if="!item.type && item.render && formData" style="flex:1;">
              <component :is="item.render({ item, value: formData[item.field], row: formData, handlers })"
                v-model="formData[item.field]" />
            </div>

            <template v-else-if="item.type === FORM_FIELD_TYPE.INPUT && item.labelField">

              <el-input v-show="false" style="width: 100%" v-model="formData[item.field]" clearable
                :placeholder="item.placeholder" v-bind="item.props" />


              <el-input style="width: 100%" v-model="formData[item.labelField]" clearable @click="formItemClick(item)"
                :placeholder="item.placeholder" v-bind="item.props" />

            </template>


            <el-input style="width: 100%" :placeholder="item.placeholder" clearable
              v-else-if="item.type === FORM_FIELD_TYPE.INPUT" v-model="formData[item.field]" v-bind="item.props" />

            <el-text style="width: 100%" v-if="item.type === FORM_FIELD_TYPE.TEXT" v-model="formData[item.field]"
              v-bind="item.props" />

            <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATE"
              v-model="formData[item.field]" :type="item.type" v-bind="item.props" value-format="YYYY-MM-DD" />
            <CitySelect  v-else-if="item.type === FORM_FIELD_TYPE.CITY_SELECT" v-model="formData[item.field]" @update:model-value="(v)=>item.onChange(v)"/>
            <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATE_RANGE"
              @change="(v)=>handleDateChange(formData, item, v)" v-model="formData[item.field]" :type="item.type"
              range-separator="至" start-placeholder="开始日期" value-format="YYYY-MM-DD" end-placeholder="结束日期"
              v-bind="item.props" />
            <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATE_TIME_RANGE"
              @change="handleDateChange(formData, item)" v-model="formData[item.field]" :type="item.type"
              range-separator="至" start-placeholder="开始日期" value-format="YYYY-MM-DD" end-placeholder="结束日期"
              v-bind="item.props" />
            <el-time-picker :is-range="true" v-else-if="item.type === FORM_FIELD_TYPE.TIMES" style="width: 100%"
              v-model="formData[item.field]" placeholder="选择时间" v-bind="item.props"
              :value-format="item.config && item.config.valueFormat || 'HH:mm'" />

            <el-time-picker :is-range="true" v-else-if="item.type === FORM_FIELD_TYPE.TIME" style="width: 100%"
              v-model="formData[item.field]" placeholder="选择时间" v-bind="item.props"
              :value-format="item.config && item.config.valueFormat || 'HH:mm:ss'" />
            <CommonSelect @change="handleSelectChange($event, item)" v-else-if="item.type === FORM_FIELD_TYPE.SELECT"
              :config="item.config" v-model="formData[item.field]" />
            <SingleLayerSelect v-else-if="item.type === FORM_FIELD_TYPE.SINGLE_LAYER_SELECT"
              v-model="formData[item.field]" :options="item.options" :clearable="item.clearable" />
          </el-form-item>
        </template>
      </div>
    </el-form>
    <div class="toolbar">
      <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      <el-button @click="expandSearch" v-if="modelValue.items.length > expandLimit" :icon="Sort">展开搜索</el-button>
      <el-button type="primary" @click="handleSearch(false)" :icon="Search">搜索</el-button>
      <el-button v-if="(!modelValue.pageConfig || (modelValue.pageConfig && modelValue.pageConfig.chooseMode != true))"
        @click="buttonClick(button)" :type="button.buttonClass || 'primary'"
        v-for="button in modelValue.buttons.filter(value => value.name != '批量删除')">{{ button.name }} </el-button>


    </div>
  </el-card>

</template>

<script setup>
import { Search, Sort, Refresh } from '@element-plus/icons-vue'
import FORM_FIELD_TYPE from '/@/constants/FormFieldType'


const { handlers } = inject('searchTablePageContext')

const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  },
  pageConfig: {

  }
})
const columnCount = props.modelValue.columnCount || '6'
const columnWidth = props.modelValue.columnWidth || '300px'
const updateModelValue = { ...props.modelValue }
const emits = defineEmits(['search', 'update:modelValue'])
const formData = ref({});
const expandStatus = ref(false)
const expandLimit = ref(props.modelValue.expandLimit || 5)
// 初始化表单数据
props.modelValue.items.forEach((item) => {
  formData.value[item.field] = item.defaultValue;
});
const handleSelectChange = (event, item) => {
  if (item && item.config && item.config.onChange) {
    item.config.onChange(formData.value[item.field]);
  }
}
// 搜索按钮事件
const handleSearch = (reset) => {
  // 用于去除日期范围选择组件默认双向绑定的字段
  const dateFieldList = props.modelValue.items.filter(x=>x.type === FORM_FIELD_TYPE.DATE_RANGE).map(x=>x.field)
  const data = {  };

  for (const key of Object.keys(formData.value)){
    if (!dateFieldList.includes(key)) {
      data[key] = formData.value[key]
    }
  }

  updateModelValue.queryParams = data
  // 只更新搜索条件
  handlers.updateSearchParams(data)
  // 触发搜索时重置页码
  handlers.execute({ page: 1 })
};
const buttonClick = (button) => {
  if (button.click) {
    button['click']({ button, handlers })
  }
}

const formItemClick = (item) => {
  if (item.labelField) {
    if (props.modelValue && props.modelValue.formItemClick) {
      props.modelValue.formItemClick({ item })


    }
  }
}

const handleDateChange = (form, config,v) => {
  console.log("value",v)
  const [startDate, endDate] = v
  
  if (config && config.startDateField && config.endDateField){
    form[config.startDateField] = startDate
    form[config.endDateField] = endDate
    form["startDateField"] = config.startDateField
    form["endDateField"] = config.endDateField
  }
  // if (config.type == 'daterange' || config.type == 'datetimerange') {
  //   let array = form[config.field];
  //   form['startCreateTime'] = array[0]
  //   form['endCreateTime'] = array[1]
  // }
}

// 重置按钮事件
const handleReset = () => {
  // formData.value['startCreateTime'] = null
  // formData.value['endCreateTime'] = null
  // 重置搜索将日期范围所绑定的两个字段数据清除
  props.modelValue.items.filter(x=>x.type === FORM_FIELD_TYPE.DATE_RANGE).forEach(x=>{
    formData.value[x.startDateField] = null
    formData.value[x.endDateField] = null
    formData.value["startDateField"] = null
    formData.value["endDateField"] = null
  })

  props.modelValue.items.forEach((item) => {
    if (item.type === FORM_FIELD_TYPE.SELECT) {
      formData.value[item.field] = [];
    } else {
      if (item.labelField) {
        formData.value[item.labelField] = null;
      }
      formData.value[item.field] = item.defaultValue || null;
    }
  });


  handleSearch(true);
};
const getFormData = () => {
  return formData.value
}

const updateFormData = (key, value) => {
  formData.value[key] = value
}


watch(() => props.modelValue.modelData, (data) => {
  // initData(data)
}, { deep: true });


const initData = (data) => {
  let fieldList = props.modelValue.items.map(value => value.field);


  for (let target of props.modelValue.items) {
    if (target && target.config) {
      let key = target['field']
      if (target.config.defaultValue != undefined) {
        formData.value[key] = target.config.defaultValue
      } else {

        if (target.config.optionsFunction) {
          let data = target.config.optionsFunction()
          console.log(data);
          if (data && data.length > 0) {
            let item = data[0]
            formData.value[key] = target.config['prop'] ? item[target.config['prop']['value']] : item['value']
          }
        }

      }
    }
  }
}
initData(props.modelValue.modelData)


const localHandlers = {
  async submit() {
    const valid = await validateForm() // 表单验证
    if (valid) {
      return handlers.execute(formModel.value)
    }
  },

  reset() {
    resetForm()
    handlers.reset()
  }
}

defineExpose({
  formData,
  getFormData,
  updateFormData
})
</script>

<style scoped>
.search-items {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.form-item {
  /* 每个表单项的默认样式 */
}

/* 当没有autoFit且指定了列数时，保持grid列数不变 */
.search-items {
  display: grid;
  gap: 0px 16px;
  grid-template-columns: repeat(v-bind(columnCount), 1fr);
  /* 固定列数 */
}

.search-items.auto-fit {
  display: grid;
  gap: 0px 16px;
  grid-template-columns: repeat(auto-fill, minmax(v-bind(columnWidth), 1fr));
  /* 自适应列数 */
}

::v-deep(.el-form-item--default) {
  margin-bottom: 0;
}

::v-deep(.el-form-item__content) {
  align-content: flex-start;
}

.toolbar {
  display: flex;
  gap: 12px 12px;
  flex-wrap: wrap;
  align-content: flex-start;
  justify-content: flex-end;
}

.el-button+.el-button {
  margin-left: 0;
}
</style>
